package com.vanysoft.business.kpi.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.vanysoft.business.kpi.entity.KpiItemRule;
import com.vanysoft.business.kpi.entity.KpiRateSetting;
import com.vanysoft.business.kpi.service.KpiRateSettingService;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.common.utils.Excel.EasyPoiUtil;
import com.vanysoft.framework.aop.VanySoftValidationException;
import com.vanysoft.framework.base.action.BaseController;
import com.vanysoft.framework.config.mvc.SessionUser;
import com.vanysoft.framework.result.ResponseUtil;
import com.vanysoft.framework.utils.JSONResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import javax.validation.ValidationException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * KPI规则处理类
 *
 * @author yu_chen
 * @date 2018-07-09 14:22
 **/
@Controller
@RequestMapping("kpi/rate")
public class KpiRateController extends BaseController {


    @Autowired
    private KpiRateSettingService kpiRateSettingService;

    /**
     * 跳转到KPIRule界面
     */
    @RequestMapping("index")
    public String toKpiRate() {
        return "kpi/rate";
    }


    /**
     * 查询所有列表数据
     *
     * @return 返回值
     */
    @RequestMapping("query/all")
    @ResponseBody
    public JSONResponse selectList() {
        List<KpiRateSetting> kpiRateSettings = kpiRateSettingService.selectAll();
        initKpiRate(kpiRateSettings);
        return ResponseUtil.success(kpiRateSettings);
    }

    /**
     * 按ID查询数据
     *
     * @param id 主键ID
     * @return 返回KPI对象
     */
    @RequestMapping("query/one")
    @ResponseBody
    public JSONResponse selectById(String id) {
        KpiRateSetting kpiRateSetting = kpiRateSettingService.selectById(id);
        return ResponseUtil.success(kpiRateSetting);
    }


    /**
     * 保存或者更新等级
     *
     * @param kpiRateSetting kpiRate
     * @return 是否保存成功或者失败
     */
    @RequestMapping("save")
    @ResponseBody
    public JSONResponse saveObject(KpiRateSetting kpiRateSetting, @SessionUser UserInfo userInfo) {
        //保存时判断数据有无交叉
        List<KpiRateSetting> kpiRateSettings = kpiRateSettingService.selectAll();
        if (checkIsAcross(kpiRateSettings, kpiRateSetting)) {
            throw new VanySoftValidationException(getMessage("error.kpi.rate.in.across"));
        }
        kpiRateSetting.setUpdateDate(LocalDateTime.now());
        kpiRateSetting.setUpdateUser(userInfo.getUsername());
        //表示保存
        KpiRateSetting rating = kpiRateSettingService.selectOne(new EntityWrapper<KpiRateSetting>()
                .eq("rating", kpiRateSetting.getRating()));
        //判断添加的等级是否存在
        if (StringUtils.isEmpty(kpiRateSetting.getId()) && rating != null) {
            throw new VanySoftValidationException(getMessage("error.kpi.rate.rating.exist"));
        }
        boolean insertOrUpdate = kpiRateSettingService.insertOrUpdate(kpiRateSetting);

        return ResponseUtil.successOrFail(insertOrUpdate);
    }


    /**
     * 按ID删除
     *
     * @param id 主键ID
     * @return 是否删除成功
     */
    @RequestMapping("delete")
    @ResponseBody
    public JSONResponse deleteObject(String id) {
        boolean b = kpiRateSettingService.deleteById(id);
        return ResponseUtil.successOrFail(b);
    }

    /**
     * 导出excel
     */
    @RequestMapping("export/excel")
    public void exportExcel() {
        List<KpiRateSetting> kpiRateSettings = kpiRateSettingService.selectAll();
        initKpiRate(kpiRateSettings);
        EasyPoiUtil.exportExcel(kpiRateSettings, "", "sheet01", KpiRateSetting.class, "kpiRateExport.xlsx", getResponse());
    }

    /**
     * 判断新增或者更新的记录是否存在交叉
     *
     * @param kpiRateSettings 记录值
     * @param newRate         新的记录
     * @return true 存在交叉 false 不存在交叉
     */
    private boolean checkIsAcross(List<KpiRateSetting> kpiRateSettings, KpiRateSetting newRate) {
        for (KpiRateSetting oldRate : kpiRateSettings) {
            if (StringUtils.equals(newRate.getId(), oldRate.getRating())) {
                continue;
            }
            //判断是否存在交叉
            boolean check = Math.max(oldRate.getScoreBefore(), newRate.getScoreBefore()) <
                    Math.min(oldRate.getScoreAfter(), newRate.getScoreAfter());
            if (check) {
                //表示存在交叉
                return true;
            }
        }
        return false;
    }


    /**
     * 初始化数据
     *
     * @param kpiRateSettings 数据
     */
    private void initKpiRate(List<KpiRateSetting> kpiRateSettings) {
        for (KpiRateSetting kpiRateSetting : kpiRateSettings) {
            kpiRateSetting.setScore(kpiRateSetting.getScoreBefore() + "~" + kpiRateSetting.getScoreAfter());
        }
    }
}